<template>
	<view class='popShopTel popShop'>
		<view class="top flex_row_btw_top">
			<view class="left flex_row_start_center">
				<text></text>
			</view>
			<view class="close">
				<up-icon name="close" color="#999" size="25" @tap="closes"></up-icon>
			</view>
		</view>
		<view class="main">
			<view class="container" v-if="!isLogin">
				<view class="login">
					<div class="lg">
						<image src="../static/image/logo.png" alt="" class="loginLogo" />
					</div>
				</view>
				<view class="form">
					<button class="btn1" :disabled="allChecked?false:true" open-type="getPhoneNumber"
						:class="!allChecked?'noClick':''" @getphonenumber="getPhoneNumber">快速登录</button>
				</view>
				<view class="tips">
					<label class="radio" @click="changeAll">
						<radio class="radio" :value="allChecked" :checked="allChecked" color="#D0A564"
							style="transform:scale(0.7);" />
						<text>已阅读并同意智装通平台<text class="tipColor">《用户协议》</text>及隐私政策</text>
					</label>
				</view>
			</view>
			<view class="containers" v-else>
				<view class="login">
					<div class="lg">
						<image src="../static/image/logo.png" alt="" class="loginLogo" />
					</div>
				</view>
				<view class="form">
					<up-form labelPosition="top" :model="userInfo" :rules="rules" ref="uForm" class="forms" :label-width="60">
						<up-form-item label="手机号" prop="phone" ref="item1" >
							<up-input v-model="userInfo.phone"  class="one" disabled
								maxlength="11"></up-input>
						</up-form-item>
						<up-form-item label="验证码" prop="code" ref="item1">
							<up-input v-model="userInfo.code"  class="two" maxlength="6">
								<template #suffix>
									<view class="getPhoneCode" v-if="!getCodeShow" @click="getCode(userInfo.phone)">
										获取验证码
									</view>
									<view class="getPhoneCode" v-if="getCodeShow">{{ timer }}秒重新获取</view>
								</template>
							</up-input>

						</up-form-item>
					</up-form>
					<view class="tipInfo">
						提示：您选择的手机号已绑定其他微信账号！如需解绑原有微信并重新绑定，请完成短信验证！
					</view>
					<button class="btn1" @click="saveInfo">验证并重新绑定微信</button>
				</view>
			</view>
		</view>
	</view>

</template>

<script setup>
import {
		wx_small_login,
		small_phone,
		get_oss_url,
		getCodeRequst,
		save
	} from '@/api/login.js'
	import {
		onMounted,
		ref
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	// 是否同意协议的状态
	const agreeToTerms = ref(false) // 默认未选中
	const wxcCode = ref('')
	const allChecked = ref(true) //隐私协议默认
	const showPhone = ref(false)
	const userInfo = ref({
		phone: '',
		code: '',
		user_id: ''
	})

	const rules = {
		'phone': [{
			type: 'string',
			required: true,
			max: 11,
			message: '请输入正确手机号',
			trigger: ['blur', 'change'],
		}, {
			pattern: /^1[3-9]\d{9}$/,
			message: '手机号格式不正确',
			trigger: 'blur'
		}],
		'code': {
			type: 'string',
			max: 6,
			required: true,
			message: '请输入验证码',
			trigger: ['blur', 'change'],
		},
	}
	//手机号未被占用
	const isLogin = ref(false)

	const sceneType = ref('')
	const emit = defineEmits(['closeModel','saveModel'])
	const closes = ()=>{
		clear()
		emit('closeModel')
	}
	onMounted(() => {
		// if (!allChecked.value) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '请先同意用户协议'
		// 	})
		// }
		sceneType.value = uni.getStorageSync('sceneType')

	})
	// 选择隐私协议
	const changeAll = () => {
		allChecked.value = !allChecked.value
	}
	let timer = ref(60);
	let t = null;
	let getCodeShow = ref(false);
	//获取验证码
	const getCode = async (phone) => {
		let res = await getCodeRequst({
			phone: phone,
			scene: '13',
			extend: userInfo.value.user_id
		})
		uni.showToast({
			icon: 'none',
			title: res.msg
		})
		if (res.code == 1) {
			getCodeShow.value = true
			if (t) clear();
			t = setInterval(() => {
				timer.value--;
				if (timer.value === 0) clear();
			}, 1000);
		} else {
			getCodeShow.value = false
		}
		console.log(res.data)
	}

	const clear = () => {
		clearInterval(t);
		timer.value = 60;
		getCodeShow.value = false;
		t = null;
	};
	// 获取手机号
	const getPhoneNumber = (e) => {
		// 检查是否同意协议
		if (!allChecked.value) {
			uni.showToast({
				icon: 'none',
				title: '请先同意用户协议'
			})
			return
		}
		// 注意：目前该接口针对非个人开发者，且完成了认证的小程序开放（不包含海外主体）。需谨慎使用，若用户举报较多或被发现在不必要场景下使用，微信有权永久回收该小程序的该接口权限。
		if (e.detail.errMsg == "getPhoneNumber:ok") {
			loginPhone(e.detail.code)
		} else {
			console.log("用户点击了拒绝")
		}
	}
	//通过微信code 获取信息
	const loginPhone = async (code) => {
		const res = await small_phone({
			code
		})
		if (res.code == 0) {
			isLogin.value = true
			uni.showToast({
				icon: 'none',
				title: res.msg
			})
			uni.setStorageSync('token', '')
			uni.setStorageSync('useInfo', '')
		} else {
			if (res.data.hasOwnProperty('phone')) {
				isLogin.value = true
				userInfo.value.phone = res.data.phone
				userInfo.value.user_id = res.data.user_id
			}
			if (res.data.hasOwnProperty('userinfo')) {
				uni.setStorageSync('token', res.data.userinfo.token)
				uni.setStorageSync('useInfo', res.data.userinfo)
				// uni.switchTab({
				// 	url: '/pages/home/index'
				// })
				if (sceneType.value) {
					uni.redirectTo({
						url: '/pages/common/index'
					})
				} else {
					uni.switchTab({
						url: '/pages/home/index'
					})
				}

			}
		}

	}
	const uForm = ref()
	//通过微信code 获取信息
	const saveInfo = async () => {
		console.log('baocun')
		if (userInfo.value.code == '') {
			uni.showToast({
				icon: 'none',
				title: '请输入验证码'
			})
			return
		}
		// uForm.value.validate(async (valid) => {
		// 	if (valid) {
		// console.log(valid)
		let obj = {
			code: userInfo.value.code,
			user_id: userInfo.value.user_id
		}
		const res = await save(obj)
		if (res.code == 0) {
			uni.showToast({
				icon: 'none',
				title: res.msg
			})
			uni.setStorageSync('token', '')
			uni.setStorageSync('useInfo', '')
		} else {
			uni.setStorageSync('token', res.data.userinfo.token)
			uni.setStorageSync('useInfo', res.data.userinfo)
			// uni.switchTab({
			// 	url: '/pages/home/index'
			// })
			if (sceneType.value) {
				uni.redirectTo({
					url: '/pages/common/index'
				})
			} else {
				uni.switchTab({
					url: '/pages/home/index'
				})
			}
		}
		// } else {
		// 	console.log('验证失败');
		// }
		// });


	}
</script>

<style scoped lang="less">
	.popShopTel {
		padding: 30rpx 30rpx 45rpx;
		background-image: url(https://zzt-pub.oss-cn-wuhan-lr.aliyuncs.com/clientImg/telBj%402x.png);
		background-repeat: no-repeat;
		background-size: 100%;
		height: auto;

		.left {
			text {
				font-weight: 500;
				font-size: 34rpx;
				color: #333333;
			}
		}

		.main {
			margin-top: 20rpx;

			.login {
				width: 100%;
				display: flex;
				justify-content: center;

				.lg {
					height: 100%;
					display: flex;
					justify-content: center;

					.loginLogo {
						width: 243rpx;
						height: 122rpx;
					}
				}
			}

			.tips {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 22rpx;
				margin-top: 70rpx;
			}

			.tipColor {
				color: #D0A564;
			}
		}

		.btn1 {
			width: 100%;
			height: 80rpx;
			background: linear-gradient(113deg, #F2BD6F 0%, #CCA05F 100%);
			border-radius: 20rpx;
			margin-top: 92rpx;
			font-family: Source Han Sans CN, Source Han Sans CN;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 80rpx;
			text-align: center;
			font-style: normal;
			text-transform: none;
		}
	}
</style>